﻿using System;
using System.Net;
using System.Net.Http;
using System.Web.Http.Filters;
using ZLWeb.WebApiEntityBase;
using ZLWeb.WebApiInfrastructure.CustomerException;


namespace ZLWeb.WebApiInfrastructure.Filter
{
    /// <summary>
    ///     异常全局处理类
    /// </summary>
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)]
    public class ExceptionAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            HandleException(actionExecutedContext);
            base.OnException(actionExecutedContext);
        }

        public virtual void HandleException(HttpActionExecutedContext actionExecutedContext)
        {
            ////其他错误通用处理
            if (actionExecutedContext.Exception is ValidateException)
            {
                var error = new ResponseResultInfo
                {
                    
                };
                actionExecutedContext.Response =
                    actionExecutedContext.Request.CreateResponse(HttpStatusCode.ServiceUnavailable, error);
            }
            //else if (actionExecutedContext.Exception is SpException)
            //{
                
            //}
            else if (actionExecutedContext.Exception is SqlExecuteException)
            {
                var dbexception =
                    actionExecutedContext.Exception as SqlExecuteException;
                var error = new ResponseResultInfo {Errormodel = dbexception.ErrorModel};
                actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(HttpStatusCode.OK, error);
            }
            //未知情况
            else
            {
                actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(HttpStatusCode.OK);
            }
        }
    }
}